package biz.datalk.industrialland.admin.modules.system.service.impl;

import biz.datalk.commons.utils.encryption.Des3Utils;
import biz.datalk.industrialland.admin.modules.system.controller.RandCodeImageContrller;
import biz.datalk.industrialland.admin.modules.system.mapper.ISysUserExtMapper;
import biz.datalk.industrialland.admin.modules.system.pojo.dto.SysLoginDTO;
import biz.datalk.industrialland.admin.modules.system.service.ISysLoginService;
import biz.datalk.industrialland.common.config.JwtCryptoCfg;
import biz.datalk.industrialland.common.def.CommonConstant;
import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.util.I18NUtil;
import biz.datalk.industrialland.common.util.JwtUtil;
import biz.datalk.industrialland.common.util.RedisUtil;
import biz.datalk.industrialland.common.util.SpringContextUtils;
import biz.datalk.industrialland.mbg.mapper.SysUserMapper;
import biz.datalk.industrialland.mbg.pojo.po.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

/**
 *
 *
 * @author tarofang@163.com
 * @date 2020-04-15
 *
 */
@Slf4j
@Service
// ISysLoginConfig 中注入
public class SysLoginServiceImpl implements ISysLoginService {

    private RedisUtil redisUtil;

    private SysUserMapper userMapper;

    private ISysUserExtMapper userExtMapper;

    public SysLoginServiceImpl(RedisUtil redisUtil, SysUserMapper userMapper, ISysUserExtMapper userExtMapper) {
        this.redisUtil = redisUtil;
        this.userMapper = userMapper;
        this.userExtMapper = userExtMapper;
    }

    @Override
    public UnifyResult login(SysLoginDTO loginDTO) {
        String username = StringUtils.trimToNull(loginDTO.getUsername()),
                password = StringUtils.trimToNull(loginDTO.getPassword()),
                captcha = StringUtils.trimToNull(loginDTO.getCaptcha()),
                captchaRan = StringUtils.trimToNull(loginDTO.getCatpchaRan());

        // 验证码验证
        String key = RandCodeImageContrller.CAPTCHA_CODE_PREFIX + captchaRan;
        String val = redisUtil.getStr(key);
        if (!StringUtils.equalsIgnoreCase(captcha, val)) {
            redisUtil.del(key);
            return UnifyResult.fail(I18NUtil.getMsg("login.captchat.wrong"));
        }
        redisUtil.del(key);

        SysUser sysUser = userExtMapper.getUserByName(loginDTO.getUsername());
        if (sysUser == null) {
            return UnifyResult.fail(I18NUtil.getMsg("login.user.no.exists"));
        }

        String syspassword = sysUser.getPassword();
        String decodePws = Des3Utils.decode(syspassword);
        if (!StringUtils.equals(decodePws, password)) {
            return UnifyResult.fail(I18NUtil.getMsg("login.password.wrong"));
        }

        String token = JwtUtil.sign(username, "");
        // 设置 TOKEN
        // redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token, JwtUtil.EXPIRE_TIME/1000);
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token, JwtCryptoCfg.getInstance().getExpire());
        // 设置当前用户最新的token, 用于判定能否多次地登录，且同时操作
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN_LATEST + username, token, JwtCryptoCfg.getInstance().getExpire());

        WebUtils.setSessionAttribute(SpringContextUtils.getHttpServletRequest(), CommonConstant.ACCESS_TOKEN, token);

        String contextPath = SpringContextUtils.getHttpServletRequest().getContextPath();
        String skipUrl = "/".equals(contextPath) ? "" : contextPath + "/sys/index";

        return UnifyResult.success().mapData().put("token", token).put("skipUrl", skipUrl);
    }

    @Override
    public UnifyResult logout() {
        // Subject subject = SecurityUtils.getSubject();
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        //清空用户Token缓存
        redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);

        WebUtils.setSessionAttribute(request, CommonConstant.ACCESS_TOKEN, null);

        //清空用户权限缓存：权限Perms和角色集合
        // redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_ROLE + sysUser.getUsername());
        // redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + sysUser.getUsername());
        return UnifyResult.success("登出成功");
    }

}
